﻿using Autodesk.AutoCAD.DatabaseServices;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Interop;
using System.Windows.Media.Imaging;
using System.Windows;
using System.Windows.Navigation;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using CADTool_LinXi;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.Windows.Shapes;
using System.Windows.Media;

namespace HaierCADplug_in
{
    /// <summary>
    /// 图片信息类
    /// </summary>
    public class ImageData : INotifyPropertyChanged
    {
        public ObservableCollection<ImageData> Images { get; set; } = new ObservableCollection<ImageData>();
        public string ImagePath { get; set; }
        public string ImageName { get; set; }
        public string Url { get; set; }
        private ImageSource _imageSource;
        public ImageSource ImageSource
        {
            get => _imageSource;
            set { _imageSource = value; OnPropertyChanged(); }
        }
        private bool isFavorited;

        public bool IsFavorited
        {
            get { return isFavorited; }
            set
            {
                if (isFavorited != value)
                {
                    isFavorited = value;
                    OnPropertyChanged("IsFavorited");
                }
            }
        }


        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        /// <summary>
        /// 加载文件下的每个图片
        /// </summary>
        /// <param name="directoryPath">文件夹路径</param>
        public void LoadImages(string directoryPath)
        {
            //获取每个文件路径
            var imageFiles = Directory.GetFiles(directoryPath, "*.*", SearchOption.TopDirectoryOnly)
                                      .Where(s => s.EndsWith(".jpg") || s.EndsWith(".png") || s.EndsWith(".jpeg") || s.EndsWith(".dwg"));
            foreach (var file in imageFiles)
            {
                try
                {
                    BitmapSource imageSource = null;
                    //判断是否为dwg格式
                    if (file.EndsWith(".dwg"))
                    {
                        imageSource = GetDwgThumbnail(file);
                    }
                    else
                    {
                        imageSource = new BitmapImage(new Uri(file));
                    }

                    if (imageSource != null)
                    {
                        //添加图像信息
                        Images.Add(new ImageData
                        {
                            ImagePath = file,
                            ImageName = System.IO.Path.GetFileName(file),
                            Url = "http://baidu.com",
                            ImageSource = imageSource
                        });
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"Failed to load image from file: {file}, Error: {ex.Message}");
                }
            }
        }

        /// <summary>
        /// dwg格式文件的缩略图转换为BitmapSource
        /// </summary>
        /// <param name="dwgFilePath">文件路径</param>
        /// <returns>BitmapSource</returns>
        private BitmapSource GetDwgThumbnail(string dwgFilePath)
        {
            try
            {
                //创建一个新的空白数据库
                using (Database db = new Database(false, true))
                {
                    //读取指定目录下的DWG文件，在读取文件时，其他进程也能读取文件，true表示可以文件格式转换
                    db.ReadDwgFile(dwgFilePath, FileShare.Read, true, "");
                    //如果DWG文件包含缩略图，则用此图像创建一个bitmap对象
                    if (db.ThumbnailBitmap != null)
                    {
                        using (var bitmap = new Bitmap(db.ThumbnailBitmap))
                        {
                            //GetHbitmap()方法从bitmap对象中获取GDI句柄，这是一个指向位图资源的指针
                            IntPtr hBitmap = bitmap.GetHbitmap();
                            try
                            {
                                //用于将 GDI 句柄转换为 WPF 中使用的 BitmapSource
                                BitmapSource source = Imaging.CreateBitmapSourceFromHBitmap(
                                   hBitmap,
                                   IntPtr.Zero,
                                   Int32Rect.Empty,
                                   BitmapSizeOptions.FromEmptyOptions());
                                source.Freeze(); // 确保在跨线程操作时，图像是冻结的
                                return source;
                            }
                            finally
                            {
                                DeleteObject(hBitmap);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Failed to load or convert thumbnail from DWG file: {ex.Message}");
            }
            return null;
        }

        [DllImport("gdi32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool DeleteObject(IntPtr hObject);

        public Bitmap get_image_of_file(string filename)
        {
            //create a new database instance and load the dwg file into it.
            Database dbb = new Database(false, true);
            dbb.ReadDwgFile(filename, FileShare.Read, false, "");

            //grab the thumbnail bitmap and get rid of the white background
            Bitmap preview = dbb.ThumbnailBitmap;
            preview.MakeTransparent(System.Drawing.Color.White);

            return preview;
        }
    }
}
